const { app, BrowserWindow, ipcMain, Menu, dialog, shell, protocol } = require('electron')
const path = require('path')
const { createProtocol } = require('vue-cli-plugin-electron-builder/lib')
const isDevelopment = process.env.NODE_ENV !== 'production'

let mainWindow = null
let httpServerWindow = null
const windows = new Map()

protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

async function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1400,
    height: 900,
    minWidth: 1200,
    minHeight: 700,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: false
    },
    icon: path.join(__dirname, '../public/icon.png'),
    titleBarStyle: 'default',
    frame: true
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    await mainWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) mainWindow.webContents.openDevTools()
  } else {
    createProtocol('app')
    mainWindow.loadURL('app://./index.html')
    mainWindow.webContents.openDevTools()
  }

  mainWindow.on('closed', () => {
    mainWindow = null
    windows.forEach(win => win.close())
    windows.clear()
  })
  Menu.setApplicationMenu(null)
  mainWindow.setMenuBarVisibility(false)
  
  // Setup HTTP server IPC handlers
  setupHttpServerIPC(mainWindow)
  
  // Setup TCP/UDP IPC handlers
  setupTcpUdpIPC(mainWindow)
  
  // createMenu()
}

function createMenu() {
  const template = [
    {
      label: '视图',
      submenu: [
        { label: '重新加载', accelerator: 'CmdOrCtrl+R', role: 'reload' },
        { label: '强制重新加载', accelerator: 'CmdOrCtrl+Shift+R', role: 'forceReload' },
        { label: '开发者工具', accelerator: 'F12', role: 'toggleDevTools' },
        { type: 'separator' },
        { label: '实际大小', accelerator: 'CmdOrCtrl+0', role: 'resetZoom' },
        { label: '放大', accelerator: 'CmdOrCtrl+Plus', role: 'zoomIn' },
        { label: '缩小', accelerator: 'CmdOrCtrl+-', role: 'zoomOut' },
        { type: 'separator' },
        { label: '全屏', accelerator: 'F11', role: 'togglefullscreen' }
      ]
    },
    {
      label: '帮助',
      submenu: [
        {
          label: '关于',
          click: () => {
            dialog.showMessageBox({
              type: 'info',
              title: '关于',
              message: 'LinkVerify',
              detail: 'Multi-Service Communication Debug Test Tool\nVersion: 1.0.0\n基于 Electron + Vue2 开发',
              buttons: ['确定']
            })
          }
        },
        {
          label: '开发文档',
          click: () => {
            shell.openExternal('https://github.com/linkverify/docs')
          }
        }
      ]
    }
  ]

  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
}

ipcMain.handle('app:get-version', () => {
  return app.getVersion()
})

ipcMain.handle('dialog:open-file', async (event, options) => {
  const result = await dialog.showOpenDialog(mainWindow, options)
  return result
})

ipcMain.handle('dialog:save-file', async (event, options) => {
  const result = await dialog.showSaveDialog(mainWindow, options)
  return result
})

ipcMain.handle('module:http-client:request', async (event, config) => {
  const axios = require('axios')
  console.log('后端收到请求:', config)
  
  // 修复 localhost IPv6 问题
  if (config.url && config.url.includes('localhost')) {
    config.url = config.url.replace('localhost', '127.0.0.1')
    console.log('转换URL为IPv4:', config.url)
  }
  
  const startTime = Date.now()
  
  try {
    const response = await axios(config)
    const endTime = Date.now()
    
    // 计算响应大小
    let size = 0
    if (response.data) {
      if (typeof response.data === 'string') {
        size = new Blob([response.data]).size
      } else {
        size = new Blob([JSON.stringify(response.data)]).size
      }
    }
    
    const result = {
      status: response.status,
      statusText: response.statusText,
      headers: response.headers,
      data: response.data,
      // 不返回config，因为它包含不能序列化的函数
      time: endTime - startTime,
      size: size
    }
    
    console.log('后端返回响应:', result)
    return result
  } catch (error) {
    const endTime = Date.now()
    console.error('请求失败:', error.message)
    
    if (error.response) {
      // 服务器返回了错误响应
      let size = 0
      if (error.response.data) {
        if (typeof error.response.data === 'string') {
          size = new Blob([error.response.data]).size
        } else {
          size = new Blob([JSON.stringify(error.response.data)]).size
        }
      }
      
      return {
        error: false,  // 改为false，因为这是一个有效的HTTP响应
        status: error.response.status,
        statusText: error.response.statusText,
        headers: error.response.headers,
        data: error.response.data,
        time: endTime - startTime,
        size: size
      }
    } else {
      // 网络错误或其他错误
      return {
        error: true,
        message: error.message,
        code: error.code,
        time: endTime - startTime
      }
    }
  }
})

// Import HTTP server manager
const { setupHttpServerIPC } = require('./main/httpServer')
const { setupTcpUdpIPC } = require('./main/tcpUdpHandler')

// Setup HTTP server IPC handlers after window is created
// This will be called in createWindow function

let mqttClient = null

ipcMain.handle('module:mqtt:connect', async (event, config) => {
  const mqtt = require('mqtt')
  
  if (mqttClient) {
    mqttClient.end()
  }

  mqttClient = mqtt.connect(config.url, {
    username: config.username,
    password: config.password,
    clientId: config.clientId || `linkverify_${Date.now()}`
  })

  mqttClient.on('connect', () => {
    mainWindow.webContents.send('mqtt:connected')
  })

  mqttClient.on('message', (topic, message) => {
    mainWindow.webContents.send('mqtt:message', {
      topic,
      message: message.toString(),
      timestamp: new Date().toISOString()
    })
  })

  mqttClient.on('error', (error) => {
    mainWindow.webContents.send('mqtt:error', error.message)
  })

  mqttClient.on('close', () => {
    mainWindow.webContents.send('mqtt:disconnected')
  })

  return { success: true }
})

ipcMain.handle('module:mqtt:subscribe', (event, topic, qos = 0) => {
  if (!mqttClient) {
    return { error: true, message: 'Not connected' }
  }
  
  mqttClient.subscribe(topic, { qos }, (err) => {
    if (err) {
      return { error: true, message: err.message }
    }
  })
  
  return { success: true }
})

ipcMain.handle('module:mqtt:publish', (event, topic, message, qos = 0, retain = false) => {
  if (!mqttClient) {
    return { error: true, message: 'Not connected' }
  }
  
  mqttClient.publish(topic, message, { qos, retain }, (err) => {
    if (err) {
      return { error: true, message: err.message }
    }
  })
  
  return { success: true }
})

ipcMain.handle('module:mqtt:disconnect', () => {
  if (mqttClient) {
    mqttClient.end()
    mqttClient = null
    return { success: true }
  }
  return { error: true, message: 'Not connected' }
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    try {
      // const installExtension = require('electron-devtools-installer').default
      // const { VUEJS_DEVTOOLS } = require('electron-devtools-installer')
      // await installExtension(VUEJS_DEVTOOLS, {
      //   loadExtensionOptions: {
      //     allowFileAccess: true
      //   },
      //   forceDownload: false
      // })
      console.log('Vue Devtools installed successfully')
    } catch (e) {
      console.warn('Vue Devtools failed to install (this is okay in production):', e.message)
      // Continue without devtools - not critical for app functionality
    }
  }
  createWindow()
})

if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}